package com.mamcharge.file.filter;

import com.alibaba.fastjson.JSONObject;
import com.mamcharge.file.common.HttpClientUtil;
import com.mamcharge.file.common.Result;
import com.mamcharge.file.common.TokenContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import com.alibaba.fastjson.JSON;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.http.HTTPException;


/***************
 * token验证拦截
 */
@Component
public class TokenAuthorFilter implements Filter {

    private static Logger logger = LoggerFactory
            .getLogger(TokenAuthorFilter.class);

    @Override
    public void destroy() {

    }

    @Value("checktoken.url")
    private String checkTokenUrl;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;

        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers","token,Origin, X-Requested-With, Content-Type, Accept");


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String token = req.getParameter("token");//header方式
        Result resultInfo = new Result();
        boolean isFilter = false;


        String method = ((HttpServletRequest) request).getMethod();
        if (method.equals("OPTIONS")) {
            rep.setStatus(HttpServletResponse.SC_OK);
        }else{


            if (null == token || token.isEmpty()) {
                resultInfo.setCode(404);
                resultInfo.setMsg("用户授权认证没有通过!客户端请求参数中无token信息");
            } else {
                if (volidateToken(token)) {
                    resultInfo.setCode(200);
                    resultInfo.setMsg("用户授权认证通过!");
                    isFilter = true;
                } else {
                    resultInfo.setCode(401);
                    resultInfo.setMsg("用户授权认证没有通过!客户端请求参数token信息无效");
                }
            }
           int errorCode= resultInfo.getCode();
            if ( errorCode== 404 || errorCode ==401) {// 验证失败
//                PrintWriter writer = null;
//                OutputStreamWriter osw = null;
//                try {
//                    osw = new OutputStreamWriter(response.getOutputStream(),
//                            "UTF-8");
//                    writer = new PrintWriter(osw, true);
//                    String jsonStr = JSON.toJSONString(resultInfo);
//                    writer.write(jsonStr);
//                    writer.flush();
//                    writer.close();
//                    osw.close();
//                } catch (UnsupportedEncodingException e) {
//                    logger.error("过滤器返回信息失败:" + e.getMessage(), e);
//                } catch (IOException e) {
//                    logger.error("过滤器返回信息失败:" + e.getMessage(), e);
//                } finally {
//                    if (null != writer) {
//                        writer.close();
//                    }
//                    if (null != osw) {
//                        osw.close();
//                    }
//                }
//                return;

                ServletOutputStream out = null;
                try {
                    out = response.getOutputStream();
                    response.setContentType("application/json; charset=utf-8");
                    String responseJSONObject = JSON.toJSONString(resultInfo);
                    //String responseJSONObject = JSON.toJSONString(customException.getResult());
                    out.write(responseJSONObject.toString().getBytes("UTF-8"));
                    out.flush();
                } catch (HTTPException e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception p) {
                            p.printStackTrace();
                        }
                    }
                    return ;
                }

            }

            if (isFilter) {
            logger.info("token filter过滤ok!");
            chain.doFilter(request, response);
            }
        }


    }
    private boolean volidateToken(String token){

        String s = HttpClientUtil.doPostJson(TokenContainer.CHECKURL, token);
        System.out.println(s);
        JSONObject result = JSONObject.parseObject(s);
        if (result.get("CODE").equals("0")){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}